package ThreadPoolDemo.bilibiliThread;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;

public class CallableAndFuture {

	public static void main(String[] args) throws InterruptedException,
			ExecutionException, TimeoutException {
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<String> submit = threadPool.submit(new Callable<String>() {

			@Override
			public String call() throws Exception {
				Thread.sleep(2000);
				return "hello";
			}
		});
		System.out.println("等待结果");
		// System.out.println("拿到结果" + submit.get(1, TimeUnit.SECONDS));
		System.out.println("拿到结果" + submit.get());
		ExecutorService threadPool1 = Executors.newFixedThreadPool(10);
		CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(
				threadPool1);
		for (int i = 0; i < 10; i++) {
			final Integer seqInteger = i;
			completionService.submit(new Callable<Integer>() {

				@Override
				public Integer call() throws Exception {
					Thread.sleep(new Random().nextInt(5000));
					return seqInteger;
				}
			});
		}
		for (int i = 0; i < 10; i++) {
			Integer integer = completionService.take().get();
			System.out.println(integer);
		}

	}
}
